package cn.px.rest.controller.sb;

import cn.px.common.model.UserInfo;
import cn.px.common.util.BeanConverterUtil;
import cn.px.common.util.BeanUtils;
import cn.px.common.util.R;
import cn.px.common.util.SecurityUtils;
import cn.px.common.validation.group.AddGroup;
import cn.px.common.validation.group.UpdateGroup;
import cn.px.dao.bean.MyVOPage;
import cn.px.dao.dto.sb.SbAllocateApplyDTO;
import cn.px.dao.entity.sb.SbAllocateApply;
import cn.px.dao.util.ExcelUtil;
import cn.px.dao.vo.export.sb.ExportSbAllocateApplyVO;
import cn.px.dao.vo.query.sb.SbAllocateApplyVO;
import cn.px.rest.log.annotation.SysLog;
import cn.px.service.sb.SbAllocateApplyService;
import lombok.AllArgsConstructor;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Description 调拨申请 控制器
 * @author 品讯科技
 * @date 2024-08
 * @Version Copyright (c) 2020,北京乾元坤和科技有限公司 All rights reserved.
 */
@RestController
@AllArgsConstructor
@RequestMapping("/sb/allocate-applies")
public class SbAllocateApplyController {

    private final SbAllocateApplyService sbAllocateApplyService;

    /**
     * 通过id查询单条记录
     *
     * @param id 主键
     * @return R
     */
    @GetMapping("/{id}")
    public R<SbAllocateApplyVO> getById(@PathVariable("id") String id) {
        return new R<>(sbAllocateApplyService.selectById(id));
    }

    /**
     * 新增记录
     *
     * @param sbAllocateApplyDTO 调拨申请DTO
     * @return R
     */
    @SysLog("新增调拨申请")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('sb-allocate-applies-add')")
    public R save(@Validated({AddGroup.class}) @RequestBody SbAllocateApplyDTO sbAllocateApplyDTO) {
        return new R<>(sbAllocateApplyService.saveModelByDTO(sbAllocateApplyDTO));
    }

    /**
     * 修改记录
     *
     * @param sbAllocateApplyDTO 调拨申请DTO
     * @return R
     */
    @SysLog("修改调拨申请")
    @PutMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('sb-allocate-applies-edit')")
    public R update(@PathVariable("id") String id, @Validated({UpdateGroup.class}) @RequestBody SbAllocateApplyDTO sbAllocateApplyDTO) {
        sbAllocateApplyDTO.setId(id);
        sbAllocateApplyService.modModelByDTO(sbAllocateApplyDTO);
//        this.startTask();
        return new R<>();
    }

    /**
     * 通过id删除一条记录
     *
     * @param id 主键
     * @return R
     */
    @SysLog("删除调拨申请")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('sb-allocate-applies-del')")
    public R removeById(@PathVariable String id) {
        sbAllocateApplyService.deleteByPrimaryKey(id);
        return new R<>();
    }

    /**
     * 批量记录
     *
     * @param ids 主键
     * @return R
     */
    @SysLog("批量删除调拨申请")
    @DeleteMapping("")
    @PreAuthorize("@pms.hasPermission('sb-allocate-applies-del')")
    public R removeIds(@RequestBody List<String> ids) {
        sbAllocateApplyService.batchDelete(ids);
        return new R<>();
    }

    /**
     * 获取分页
     *
     * @param pageNum            当前页码
     * @param pageSize           每页条数
     * @param sbAllocateApplyDTO 调拨申请DTO
     * @return R
     */
    @GetMapping("/page")
    public R<MyVOPage<SbAllocateApplyVO>> query(SbAllocateApplyDTO sbAllocateApplyDTO, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "20") int pageSize) {
        return new R<>(sbAllocateApplyService.selectPageList(sbAllocateApplyDTO, pageNum, pageSize));
    }

    /**
     * 获取分页
     *
     * @param pageNum            当前页码
     * @param pageSize           每页条数
     * @param sbAllocateApplyDTO 调拨申请DTO
     * @return R
     */
    @GetMapping("/apply/page")
    public R<MyVOPage<SbAllocateApplyVO>> userPage(SbAllocateApplyDTO sbAllocateApplyDTO, @RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "20") int pageSize) {
        return new R<>(sbAllocateApplyService.selectApplyPage(sbAllocateApplyDTO, pageNum, pageSize));
    }

    /**
     * 获取列表
     *
     * @param sbAllocateApplyDTO 调拨申请DTO
     * @return R
     */
    @GetMapping("")
    public R query(SbAllocateApplyDTO sbAllocateApplyDTO) {
        return new R<>(sbAllocateApplyService.getModelListByDTO(sbAllocateApplyDTO));
    }

    /**
     * 调拨申请导出
     *
     * @param sbAllocateApplyDTO 调拨申请DTO
     * @return R
     */
    @GetMapping("/export")
    @SysLog("调拨申请导出")
    @PreAuthorize("@pms.hasPermission('sb-allocate-applies-export')")
    public void export(HttpServletResponse response, SbAllocateApplyDTO sbAllocateApplyDTO) {
        List<SbAllocateApply> list = sbAllocateApplyService.getModelListByDTO(sbAllocateApplyDTO);
        ExcelUtil.exportResponseDict(response, ExportSbAllocateApplyVO.class, BeanConverterUtil.copyListProperties(list, ExportSbAllocateApplyVO.class), "调拨申请");
    }

    private void startTask() {
        UserInfo userInfo = SecurityUtils.getUserInfo();

        RuntimeService runtimeService = BeanUtils.getBean(RuntimeService.class);
        TaskService taskService = BeanUtils.getBean(TaskService.class);

        // 开始流程
//        ProcessInstance vacationInstance = runtimeService.startProcessInstanceByKey("305001");
        List<ProcessInstance> list = runtimeService.createProcessInstanceQuery().list();
        ProcessInstance vacationInstance = runtimeService.startProcessInstanceByKey("process");
//        ProcessInstance vacationInstance = runtimeService.createProcessInstanceQuery().processInstanceId("305001").singleResult();
        // 查询当前任务
//        Task currentTask = taskService.createTaskQuery().processInstanceId(vacationInstance.getId()).singleResult();
        Task task = taskService.createTaskQuery().processInstanceId(vacationInstance.getId()).singleResult();
        System.err.println(task.getId());
//        // 申明任务
//        taskService.claim(task.getId(), userInfo.getRealName());
//        Map<String, Object> vars = MapUtils.newHashMap(4);
//        vars.put("applyUser", userInfo.getRealName());
//        vars.put("days", 200);
//        vars.put("reason", "开始");
//        // 完成任务
//        taskService.complete(task.getId(), vars);
    }

    /**
     * 修改记录
     *
     * @param sbAllocateApplyDTO 调拨申请DTO
     * @return R
     */
    @SysLog("审核调拨申请")
    @PutMapping("/audit/{id}")
    public R audit(@PathVariable("id") String id, @Validated({UpdateGroup.class}) @RequestBody SbAllocateApplyDTO sbAllocateApplyDTO) {
        sbAllocateApplyDTO.setId(id);
        sbAllocateApplyService.audit(sbAllocateApplyDTO);
        return new R<>();
    }
}
